package online.chazi.bootplus.autoconfiguation.multiple.datasource.aspect;

import online.chazi.bootplus.autoconfiguation.multiple.datasource.annotation.UsingDataSource;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-05-19 13:51
 */
public class DataSourceAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {

    private Advice advice;
    private Pointcut pointcut;

    public DataSourceAdvisor(DataSourceInterceptor interceptor) {
        this.advice = interceptor;
        this.pointcut = this.buildPointcut();
    }

    private Pointcut buildPointcut() {
        //类级别的匹配
        Pointcut classPointCut = new AnnotationMatchingPointcut(UsingDataSource.class, true);
        //方法级别的匹配
        Pointcut methodPointCut = AnnotationMatchingPointcut.forMethodAnnotation(UsingDataSource.class);
        return new ComposablePointcut(classPointCut).union(methodPointCut);
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }

    @Override
    public Advice getAdvice() {
        return this.advice;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (this.advice instanceof BeanFactoryAware) {
            ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
        }
    }
}
